var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var uuid = require('node-uuid');
var Log = require('../utils/logger');
var dbManager = require('../utils/db-manager');
var ObjectID = require('mongodb').ObjectID;

router.use(bodyParser.json()); // for parsing application/json
router.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

router.restPath = "/test-code";

/* new test */
router.post('/', function (req, res, next) {
    var logger = Log.getLogger("upload test code");

    //TODO:check the request body
    var testCode = req.body;

    if(testCode.name==undefined) {
        logger.error("Test code: name is required");
        res.status(404).json({
            message: "Test code: name is required"
        });
        return;
    }

    var testCodeCollection = dbManager.db.collection('TestCode');
    testCodeCollection.insertOne(testCode).then(function(result){
        //location header of the response
        logger.info("test code created: "+ testCode.toJSON);
        res.location(router.restPath + "/" + testCode._id);
        res.status(201).end();
    }, function (error){
        logger.error("Save to collection:TestCode failed");
        res.status(405).end();
    });

});

router.get('/', function (req, res, next){
    var logger = Log.getLogger("get test code list");

    //TODO:check the request body
    var testCodeCollection = dbManager.db.collection('TestCode');
    testCodeCollection.find({}).toArray(function(error, result){
        if(error){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })

});

router.get('/:id', function (req, res, next){
    var codeId = req.params.id;
    var logger = Log.getLogger("get test code with id" );
    logger.info(codeId);

    //TODO:check the request body
    var obID;
    try {
        obID = new ObjectID(codeId);
    } catch (error) {
        var msg = {
            name:"new ObjectID error",
            message:error.toString()
        };
        logger.error(msg);
        res.status(404).json(msg).end();
        return;
    }
    var testCodeCollection = dbManager.db.collection('TestCode');
    testCodeCollection.find({_id: obID}).toArray(function(error, result){
        if(error){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })

});

module.exports = router;